<template>
<div>  
     <el-dialog  title="新建表" :visible="true" @close="cancel()" destroy-on-close width="1000px"> 
         <el-form :model="tableForm" :rules="rules" ref="tableFormRef" label-width="80px" >
            <el-form-item label="表名" prop="tableName">
                <el-input v-model="tableForm.tableName"></el-input>
            </el-form-item>
            <el-form-item label="表备注" prop="tableComment">
                <el-input v-model="tableForm.tableComment"></el-input>
            </el-form-item>
        </el-form>
        <div class="btnList">
             <el-button type="primary" icon="el-icon-plus" size="small" @click="newTable">新建表</el-button>
             <el-button  size="mini" @click="copyTable">复制表</el-button>
             <el-button  size="mini" @click="fieldsBtn">常用字段</el-button>
             <el-button  size="mini" @click="importDraft">导入草稿</el-button>
             <el-button  size="mini" @click="saveDraft">保存草稿</el-button>
             <el-button  size="mini" @click="release">发布</el-button>
        </div>
        <el-form class="baseTable" ref="baseForm" :model="baseForm">
            <el-table :data="baseForm.tableList"  @row-click="selectItem" height="400">
                <el-table-column prop="columnName" label="列名" align="center">
                    <template slot-scope="scope">
                        <el-form-item :prop="'tableList.'+scope.$index+'.columnName'" >
                            <el-input v-model="scope.row.columnName" placeholder="请输入" clearable @focus="$refs.baseForm.clearValidate(`tableList.${scope.$index}.columnName`)"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="columnType" label="数据类型" align="center">
                    <template slot-scope="scope">
                        <el-form-item :prop="'tableList.'+scope.$index+'.columnType'" >
                            <el-select
                                    v-model="scope.row.columnType"
                                    @change="
                                        () => {
                                            scope.row.field = '';
                                        }
                                    "
                                    >
                                    <el-option
                                        v-for="(item, index) in typeList"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                 </el-option>
                            </el-select>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="columnLength" label="长度" align="center">
                    <template slot-scope="scope">
                        <el-form-item :prop="'tableList.'+scope.$index+'.columnLength'" >
                            <el-input v-model="scope.row.columnLength" placeholder="请输入" clearable @focus="$refs.baseForm.clearValidate(`tableList.${scope.$index}.columnLength`)"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="allowEmpty" label="允许空" align="center">
                    <template slot-scope="scope">
                        <el-form-item :prop="'tableList.'+scope.$index+'.allowEmpty'" >
                            <el-switch v-model="scope.row.allowEmpty"></el-switch>
                        </el-form-item>
                    </template>
                </el-table-column>
                 <el-table-column prop="primayKeyStatus" label="主键" align="center">
                    <template slot-scope="scope">
                        <el-form-item :prop="'tableList.'+scope.$index+'.primayKeyStatus'" >
                            <el-switch v-model="scope.row.primayKeyStatus"></el-switch>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="columnComment" label="说明" align="center">
                    <template slot-scope="scope">
                        <el-form-item :prop="'tableList.'+scope.$index+'.columnComment'" >
                            <el-input v-model="scope.row.columnComment" placeholder="请输入" clearable @focus="$refs.baseForm.clearValidate(`tableList.${scope.$index}.columnComment`)"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <div class="flex-c-a">
                            <el-button type="text" size="small" @click.native.prevent="cancelClick(scope.$index, baseForm.tableList)">取消</el-button>
                            <el-button type="text" size="small">复制</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
     </el-dialog>
     <el-dialog  title="复制表" :visible.sync="copyFlag" width="1000px" append-to-body @close='cancelCopy'> 
        <div class="copyTable">
            <div class="contents">
                <p class="head_title">数据库目录</p>
                 <el-tree :data="treeData" :props="defaultProps"  node-key="id" 
                   ref="tree" default-expand-all highlight-current @node-click="handleNodeClick"/>
            </div>
            <div class="info">
                <div style="height: 100%">
                    <p class="head_title">数据表信息</p>
                    <div>
                        <el-input v-model="searchText" placeholder="请输入要查询的关键字" size="small" style="width: 200px">
                        </el-input>
                        <el-button style="marginLeft: 10px" type="primary" size="small" @click="searchChange">搜索</el-button>
                        <el-button style="marginLeft: 10px" size="small" @click="reset">重置</el-button>
                    </div>
                    <div class="table">
                         <el-table
                            ref="multipleTable"
                            :data="copyTableData"
                            stripe
                            style="width: 100%; marginTop: 10px"
                            size="small"
                            height="320"
                            @selection-change="handleCopyChange"
                            v-loading="copyLoading"
                            class="tableInfo"
                            row-key="id"
                        >
                            <el-table-column
                                type="selection"
                                width="55">
                            </el-table-column>
                             <el-table-column
                                prop="tableName"
                                label="表名"
                                show-overflow-tooltip
                             ></el-table-column>
                            <el-table-column
                                prop="tableComment"
                                label="表备注"
                                show-overflow-tooltip
                             ></el-table-column>
                             <el-table-column
                                prop="tableRows"
                                label="记录数"
                                show-overflow-tooltip
                             ></el-table-column>
                             <el-table-column
                                prop="dataLength"
                                label="使用大小"
                                show-overflow-tooltip
                             ></el-table-column>
                             <el-table-column
                                prop="indexLength"
                                label="索引使用大小"
                                show-overflow-tooltip
                             ></el-table-column>
                         </el-table>
                    </div>
                    <div class="buttonCopy">
                        <el-button size="small" @click="cancelCopy">取消</el-button>
                        <el-button type="primary" size="small" @click="submitCopy">确定</el-button>
                    </div>
                </div>
            </div>
        </div>
     </el-dialog>
    <el-dialog  title="常用字段" :visible.sync="commonFieldsFlag" width="1000px" append-to-body @close='cancelFields'> 
        <div class="info main-container-parent">
            <div style="height: 100%">
                <p class="head_title">数据表信息</p>
                <div>
                    <el-input v-model="searchFields" placeholder="请输入要查询的关键字" size="small" style="width: 200px">
                    </el-input>
                    <el-button style="marginLeft: 10px" type="primary" size="small" @click="searchChangeFields">搜索</el-button>
                    <el-button style="marginLeft: 10px" size="small" @click="resetFields">重置</el-button>
                </div>
                <div class="table">
                  <el-table
                    ref="multipleTable"
                    :data="commonTableData"
                    stripe
                    style="width: 100%; marginTop: 10px"
                    size="small"
                    @selection-change="handleCommonChange"
                    v-loading="commonLoading"
                    class="tableInfo"
                    height="320"
                    row-key="id"
                >
                    <el-table-column
                        type="selection"
                        width="55">
                    </el-table-column>
                        <el-table-column
                        prop="columnName"
                        label="列名"
                        show-overflow-tooltip
                        ></el-table-column>
                    <el-table-column
                        prop="columnComment"
                        label="描述"
                        show-overflow-tooltip
                        ></el-table-column>
                    <el-table-column
                        prop="creator"
                        label="创建人"
                        show-overflow-tooltip
                        ></el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建时间"
                        show-overflow-tooltip
                        >
                         <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    </el-table>
                </div>
                <div class="buttonCopy">
                    <el-button size="small" @click="cancelFields">取消</el-button>
                    <el-button type="primary" size="small" @click='submitFields'>确定</el-button>
                </div>
            </div>
        </div>
     </el-dialog>
     <el-dialog  title="导入草稿" :visible.sync="draftFlag" width="1000px" append-to-body @close='cancelDraft'> 
        <div class="info main-container-parent">
            <div style="height: 100%">
                <p class="head_title">数据表信息</p>
                <div>
                    <el-input v-model="searchDraft" placeholder="请输入要查询的关键字" size="small" style="width: 200px">
                    </el-input>
                    <el-button style="marginLeft: 10px" type="primary" size="small" @click="searchChangeDraft">搜索</el-button>
                    <el-button style="marginLeft: 10px" size="small" @click="resetDraft">重置</el-button>
                </div>
                <div class="table">
                    <el-table
                    ref="multipleTable"
                    :data="importTableData"
                    stripe
                    style="width: 100%; marginTop: 10px"
                    size="small"
                    @selection-change="handleImportChange"
                    v-loading="importLoading"
                    class="tableInfo"
                    height="320"
                    row-key="id"
                >
                    <el-table-column
                        type="selection"
                        width="55">
                    </el-table-column>
                        <el-table-column
                        prop="tableName"
                        label="列名"
                        show-overflow-tooltip
                        ></el-table-column>
                    <el-table-column
                        prop="tableComment"
                        label="描述"
                        show-overflow-tooltip
                        ></el-table-column>
                    <el-table-column
                        prop="creator"
                        label="创建人"
                        show-overflow-tooltip
                        ></el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建时间"
                        show-overflow-tooltip
                        >
                         <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                   </el-table-column>
                    </el-table>
                </div>
                <div class="buttonCopy">
                    <el-button size="small" @click="cancelDraft">取消</el-button>
                    <el-button type="primary" size="small" @click="submitDraft">确定</el-button>
                </div>
            </div>
        </div>
     </el-dialog>
    </div>
</template>
<script>
import { getDraftList, creatDraft, getCommonList, getLibraryData,getColumnList, createTable} from '@/api/dataManagement/dataFields'
export default{
    props: {
        treeData: Array,
        selectTreeData: String
    },
    data() {
        return {
            tableForm: {},
            index: 0,
            rules: {
                tableName: [
                    { required: true, message: '请输入表名', trigger: 'blur' },
                ],
                tableComment: [
                    { required: true, message: '请输入表备注', trigger: 'blur' },
                ],
            },
            baseForm: {
                tableList: []
            },
            typeList: [
                {id: 1, label: 'varchar',value: 'varchar'},
                {id: 2, label: 'int',value: 'int'},
                {id: 3, label: 'double',value: 'double'},
                {id: 4, label: 'text',value: 'text'},
                {id: 5, label: 'datetime',value: 'datetime'},
                {id: 6, label: 'float',value: 'float'},
            ],
            copyFlag: false,
            searchText: '',
            commonFieldsFlag: false,
            searchFields: '',
            draftFlag: false,
            searchDraft: '',
            dataDirectory: [],
            defaultProps: {
                children: 'ipGroupChildren',
                label: 'labelName'
            },
            copyTableData: [],  //复制表 -- 数据表信息
            copyLoading: false,
            multipleSelectionCopy: [], //复制表  多选
            commonTableData: [], //常用字段
            commonLoading: false,
            multipleSelectionCommon: [], //常用字段  多选
            importTableData: [],  // 导入草稿
            importLoading: false,
            multipleSelectionImport: [], //导入草稿  多选
            selcetTree: {}
        }
    },
    created(){
    },
    methods: {
        handleNodeClick(data) {
            this.selcetTree = data
            this.getTableList()
        },
        getTableList() {
            if(JSON.stringify(this.selcetTree) == '{}'){
                this.$message.warning('请先选择数据库')
                return
            }
            this.copyLoading = true
            let dataList = {
                id: this.selcetTree.id,
                keyword: this.searchText
            }
            getLibraryData(dataList).then((res) => {
                if(res.code === 0){
                    this.copyTableData = res.data
                    this.copyLoading = false
                }
            })
        },
        cancel() {
            this.$emit('closeNewTable')
            this.clear()
        },
        clear() {
            this.baseForm.tableList = []
            this.tableForm = {}
        },
        newTable() {
            const newLine = {
                columnName: "",
                columnLength: "",
                columnType: '',
                empty: false,
                primayKeyStatus: false,
                columnComment: '',
                index: this.baseForm.tableList.length,
            }
            this.baseForm.tableList.push(newLine)
        },
        selectItem(row, column, event) {
             if(event.target.innerText == '复制'){
                this.copyClick(row)
            }
        },
        cancelClick(index) {
            this.baseForm.tableList.splice(index, 1)
        },
        copyClick(params) {
            let index = this.baseForm.tableList.length
            let data = JSON.parse(JSON.stringify(params))
            data.index = index
            this.baseForm.tableList.push(data)
        },
        saveDraft() {
             var reg=/^[a-zA-Z][a-zA-Z0-9_]*$/;
            if (!reg.test(this.tableForm.tableName)) {
               this.$message.warning('表名必需以字母开头,只能包括字母、数字、下划线')
                return 
            }else if(!this.tableForm.tableName) {
                this.$message.warning('请输入表名')
                return
            }else if(!this.tableForm.tableComment){
                this.$message.warning('请输入表备注')
                return
            }
            const data = {
                ...this.tableForm,
                content: JSON.stringify(this.baseForm.tableList)
            }
            creatDraft(data).then((res) => {
                if(res.code === 0){
                    this.$message.success('保存草稿成功')
                    this.$emit('sumbitNewTable')
                }
            })
        },
        release() {
             var reg=/^[a-zA-Z][a-zA-Z0-9_]*$/;
            if (!reg.test(this.tableForm.tableName)) {
               this.$message.warning('表名必需以字母开头,只能包括字母、数字、下划线')
                return 
            }else if(!this.tableForm.tableName) {
                this.$message.warning('请输入表名')
                return
            }else if(!this.tableForm.tableComment){
                this.$message.warning('请输入表备注')
                return
            }
            const data = {
                ...this.tableForm,
                id: this.selectTreeData,
                rdbColumnVoList: this.baseForm.tableList
            }
            createTable(data).then((res) => {
                if(res.code === 0){
                    this.$message.success('发布成功')
                    this.$emit('sumbitNewTable')
                }
            })
        },
        copyTable() {
            this.copyFlag = true
        },
        searchChange() {
            this.getTableList()
        },
        reset() {
            this.searchText = ''
            this.getTableList()
        },
        cancelCopy() {
            this.searchText = ''
            this.selcetTree = {}
            this.copyTableData = []
            this.$refs.tree.setCurrentKey(null)
            this.copyFlag = false
        },
        submitCopy() {
            const arr = [],tableNameList = [],dataList = []
            this.multipleSelectionCopy.map((_) => tableNameList.push(_.tableName))
            const data = {
                id: this.selcetTree && this.selcetTree.id,
                tableNameList: tableNameList
            }
            getColumnList(data).then((res) => {
                if(res.code === 0){
                     res.data.rowObject && res.data.rowObject.map((_,index) => {
                         arr.push({
                            ..._,
                            index: this.baseForm.tableList.length +index
                        })
                     })
                    this.baseForm.tableList.push(...arr)
                    this.cancelCopy()
                }
            })
        },
        fieldsBtn() {
            this.commonFieldsFlag = true
            this.getCommonData()
        },
        getCommonData() {
            this.commonLoading = true
             const data = {
                keyword: this.searchFields
            }
            getCommonList(data).then((res) => {
                if(res.code === 0){
                    this.commonLoading = false
                    this.commonTableData = res.data
                }else{
                    this.commonLoading = false
                }
            })
        },
        searchChangeFields() { //常用字段搜索
            this.getCommonData()
        },
        resetFields() {
            this.searchFields = ''
            this.getCommonData()
        },
        cancelFields() {
            this.searchFields = ''
            this.commonFieldsFlag = false
        },
        submitFields() {
            this.commonFieldsFlag = false
             let arr = []
             console.log(arr)
             this.multipleSelectionCommon && this.multipleSelectionCommon.map((_,index) => {
                arr.push({
                    ..._,
                    index: this.baseForm.tableList.length +index
                })
             })
            this.baseForm.tableList.push(...arr)
        },
        importDraft() {
            this.draftFlag = true
            this.importLoading = true
            this.getDraftList()
        },
        getDraftList() {
            const data = {
                keyword: this.searchDraft
            }
            getDraftList(data).then((res) => {
                if(res.code === 0){
                    this.importLoading = false
                    this.importTableData = res.data
                }else{
                    this.importLoading = false
                }
            })
        },
        searchChangeDraft() {
            this.importLoading = true
            this.getDraftList()
        },
        cancelDraft() {
            this.draftFlag = false
            this.searchDraft = ''
        },
        submitDraft() {
             this.draftFlag = false
            let arr = [],arr1 = []
            this.multipleSelectionImport && this.multipleSelectionImport.map((_) => arr.push(...JSON.parse(_.content)))
             console.log(arr)
             arr.map((_,index) => {
                arr1.push({
                    ..._,
                    index: this.baseForm.tableList.length +index
                })
             })
             this.baseForm.tableList.push(...arr1)
        },
        resetDraft() {
            this.searchDraft = ''
            this.importLoading = true
            this.getDraftList()
        },
        handleCopyChange(val) { //复制表 选择
            this.multipleSelectionCopy = val
        },
        handleCommonChange(val) {
            this.multipleSelectionCommon = val
        },
        handleImportChange(val) { //导入草稿
            this.multipleSelectionImport = val
        }
    }
}
</script>

<style scoped lang="scss">

    // 修改选中的样式
    ::v-deep.el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
        color: #368fff;
    }
    /* 设置滚动条的样式 */

    ::-webkit-scrollbar {
        width:12px;
    }

    /* 滚动槽 */

    ::-webkit-scrollbar-track {
        -webkit-box-shadow:inset006pxrgba(0,0,0,0.3);
        border-radius:10px;
    }

    /* 滚动条滑块 */
    ::-webkit-scrollbar-thumb {
        border-radius:10px;
        background:rgba(0,0,0,0.1);
        -webkit-box-shadow:inset006pxrgba(0,0,0,0.5);
    }

    ::-webkit-scrollbar-thumb:window-inactive {
        background:rgba(255,0,0,0.4);
    }
    .btnList{
        text-align: end;
        margin-bottom: 20px;
    }
    .baseTable{
        ::v-deep .el-form-item{
            margin-bottom: 0 !important;
        }
    }
    .copyTable{
        display: flex;
        height: 450px;
        .contents{
            flex-basis: 20%;
            height: 100%;
            overflow: scroll;
        }
        .info{
            flex-basis: 80%;
            margin-left: 20px;
        }
        
    }
     .buttonCopy{
        position: absolute;
        bottom: 20px;
        right: 20px;
    }
    .head_title{
        font-size: 12px;
        font-weight: 700;
        width: 100%;
        border-bottom: 1px solid #f2f2f2;
        margin-top: -10px;
        line-height: 40px;
        color: #4d4d4d;
    }
    .main-container-parent{
        height: 450px;
    }
    .table{
        height: calc(100% - 120px);
    }
</style>
